/* 
 * File:   server.c
 * Author: cuongnm
 *
 * Created on October 5, 2009, 11:49 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<string.h>
#include<stddef.h>
#include <time.h>
#define SERV_UDP_PORT 30346  /*any large number will do*/
#define SIZE 128
/*
 * 
 */
int main(int argc, char** argv){
       int                   sockfd, clilen,n;
       struct sockaddr_in    serv_addr, cli_addr;  /*we assume this responder
                                   is a server and the intiator is a client*/
       char                  msg[SIZE];
       char                  ack[SIZE];
       char                  bye[SIZE];
       int                   iLen;
       int                   i;
       struct tm *p;
       
        /* Open a UDP socket (an Internet datagram socket) */

       if ( (sockfd = socket (PF_INET, SOCK_DGRAM, 0)) < 0)
           printf("\n server: can't open datagram socket");  /*we assume  
                              this performs perror() and exit(-1)*/
      


       /* Bind our local address so that the client can send to us */
       bzero((char *) &serv_addr, sizeof(serv_addr));
       serv_addr.sin_family      = AF_INET;
       serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
       serv_addr.sin_port        = htons(SERV_UDP_PORT);

       if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
           printf("server: can't bind local address");

       for (;;){
           clilen = sizeof(cli_addr);
           if ((n = recvfrom(sockfd, msg, SIZE, 0,(struct sockaddr *)&cli_addr, &clilen)) < 0){
              printf("\n server: recvfrom error");
           }
           if(n!=0){
               printf("%s\n",msg);
               time_t lt;
               if(strcmp(msg,"Bonjour")==0){
               for(i=0;i<60;i++){
               lt = time(NULL);
               time (&lt );
               p = gmtime(&lt);
               sprintf(ack,"Il est %2d:%2d:%2d", p->tm_hour+7,p->tm_min,p->tm_sec);
               //printf("\n %s",ack);
               n=strlen(ack);
               if ( sendto(sockfd, ack, n, 0, (struct sockaddr *)&cli_addr, clilen) != n)
               printf("server: sendto error"); 
               sleep(1);
               }
               strcpy(bye,"Au revoir");
               if ( sendto(sockfd, bye, strlen(bye), 0, (struct sockaddr *)&cli_addr, clilen) != strlen(bye))
               printf("server: sendto error"); 
               }
               
           }
       }
    
    return (EXIT_SUCCESS);
}

